/**********************************************************************
 *  
 *
 * @url: /services/apexrest/rest
 * @data:
 *  {
        
    }
*************************************************************************/


//@RestResource(urlMapping='/CRM/upsertExWareEquipmentREST')
global with sharing class UpsertExWareEquipmentREST {

  /*
    @HttpPost
    global static RestReturnMessage doPost() {

    RestReturnMessage message = null;

    	String ts = null ; 
    	try {
    	    ts  = [select Ts__c from InstrumentConfirmationD__c  order by Ts__c desc limit 1 ].Ts__c.format('yyyy-MM-dd HH:mm:ss');
    	}catch (Exception e) {
    	    ts = '2019-01-02 00:00:00';
    	}
    	String url = Label.queryResposityURL;
     	String whereStr = ' and h.tlastmoditime > \''+ ts +'\' ' ;
    	HttpRequest req = new HttpRequest();
     	String sql = '{"data":" '+ getSql()+whereStr+'"}';
     	  System.debug(sql);
      	req.setBody(sql);
      	req.setMethod('POST');
      	req.setHeader('Content-Type','text/plain');
      	req.setEndpoint(url);
      	HttpResponse res = Utils.postRequest(req, 2);
      ///返回结果处理
        if (res.getStatusCode() == 200) {
        	System.debug(res.getBody());
        	Map<String,Object> r = null;
              //如果是测试
                if(Test.isRunningTest()){
                  Map<String,Object>  resBody= new Map<String,Object>();
                  resBody.put('code','0');
                  resBody.put('result','{"result_msg":"查询成功！","result":1,"data":[{"cgeneralbid":"1010ZG100000000CZOYH","vuserdef9":"否","selfno":"0218-07-A-0010","type":"销售出库","payaccount":"0001A0100000000RNUFR","signpsn":"李鑫鑫","cgeneralhid":"1010ZG100000000CZOYG","djh":"XC10181211348","createpsn":"王佳","vbatchcode":"20180201","spec":"R 01","invname":"干式荧光免疫分析仪","vnote":"1 公文：集贤县人民医院无合同后端实施申请-迈克POCT-R01","unitcode":"MKSY","num":"1","signdate":"2018-12-29","vbilltypename":"销售出库","serialno":"IM9101001","nccode":"100020300001","model":"R 01","tlastmoditime":"2018-12-29 08:57:41","swjhdj":"8090.4265","djdate":"2018-12-29","nciccode":"0001A0100000000RNUFR"}]}');
                    r =  resBody;
                }else{
                  r= (Map<String,Object> ) JSON.deserializeUntyped(res.getBody());
                }
        	if(r.get('code') == 0 || r.get('code') == '0'){
        		 Map<String,Object> rs = (Map<String,Object>) JSON.deserializeUntyped(((String)r.get('result')));
	            if( rs.get('result') == 1 ){

	            	SavePoint sp = Database.setSavepoint();
	            	try {
	            	    
	            	    List<Object> datas = (List<Object>)rs.get('data');
		                Map<String ,String> accMap = new Map<String,String>();
		                Map<String ,String> prodMap = new Map<String,String>();
                    Map<String,List<InstrumentConfirmationBean>>  exMap = new Map<String,List<InstrumentConfirmationBean>>();
		                Map<String,String > ks = new Map<String,String >();
                    Set<String> dks = new Set<String >();

                    Map<String,String> comMap = ImportObject.getPicklistValues('Contract__c','Corpcode__c',true);

		                Map<String,InstrumentConfirmationBean> lmMap = new Map<String,InstrumentConfirmationBean>();
		               	for(Object o : datas){
		               		Map<String,Object> mo = (Map<String,Object>)o;
		               		accMap.put( String.valueOf(mo.get('nciccode')), null);
		               		accMap.put( String.valueOf(mo.get('payaccount')), null);
		               		prodMap.put( String.valueOf(mo.get('nccode')), '');



		            
		               		ks.put(String.valueOf(mo.get('djh')).trim(),null );

		               		//lmMap.put(k,new InstrumentConfirmationBean(mo));
                       List<InstrumentConfirmationBean> tmp = new List<InstrumentConfirmationBean>();
                       if(exMap.containsKey(String.valueOf(mo.get('djh')).trim())){

                        tmp.addAll(exMap.get(String.valueOf(mo.get('djh')).trim()));

                       }

                      String company = comMap.get(String.valueOf(mo.get('unitcode')));
                      System.debug(comMap);
                      if(company == null ) return  Utils.getRestReturnMessage(false,'单号: '+String.valueOf(mo.get('djh'))+'salesforce 没维护对应公司编码:'+String.valueOf(mo.get('unitcode')) +Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

                       InstrumentConfirmationBean ib = new InstrumentConfirmationBean(mo,company ) ;
                        dks.add(ib.djh+ib.exWarehouseDetail+ib.emi+ib.vbatchcode);                  
                       tmp.add(ib);

                       exMap.put(String.valueOf(mo.get('djh')),tmp);
		               	}
		               	for(Product__c p: [ select Id,NCCode__c from Product__c where NCCode__c in:prodMap.keySet()]){
		               		prodMap.put(p.NCCode__c,p.Id);

		               	}
		               	for(Account acc : [select Id ,NCICCode__c  from Account where NCICCode__c in: accMap.keySet() ]){
		               		accMap.put(acc.NCICCode__c, acc.Id);
		               	}


		               	for(InstrumentConfirmation__c inf :[select Id ,ExWarehouse__c  from InstrumentConfirmation__c where ExWarehouse__c in:ks.keySet() ]){

                      ks.put(inf.ExWarehouse__c, inf.Id );
		               		
		               	}
                    Map<String,String> infdIDMap = new Map<String,String>();
                    for(InstrumentConfirmationD__c infd :[select Id,Only__c from InstrumentConfirmationD__c where ExWarehouse__c in:dks ]){

                      infdIDMap.put(infd.Only__c, infd.Id);

                    }

                    List<InstrumentConfirmation__c> icfList = new List<InstrumentConfirmation__c> ();
                   List<InstrumentConfirmationD__c> icfdList = new List<InstrumentConfirmationD__c>();
                    for (String key : exMap.keySet() ) {
                      
                        InstrumentConfirmation__c icf = new InstrumentConfirmation__c();
                        List<InstrumentConfirmationBean> ibL =  exMap.get(key);
                        icf.Id  = ks.get(key);
                        if( accMap.get(ibL[0].account_pk ) == null  )  return  Utils.getRestReturnMessage(false,'单号: '+ ibL[0].djh+'salesforce 没有对应的客户!客户pk:'+ibL[0].account_pk +Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

                        icf.Account__c =  accMap.get(ibL[0].account_pk ) ;
                        if( accMap.get(ibL[0].payaccount_pk ) == null )  return  Utils.getRestReturnMessage(false,'单号: '+ibL[0].djh+'salesforce 没有对应的客户!客户pk:'+ibL[0].payaccount_pk +Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

                        icf.NCAccount__c = accMap.get(ibL[0].payaccount_pk );

                        icf.ExWarehouse__c = ibL[0].djh;
                        icf.ExWareCompany__c = ibL[0].company;
                        icf.EndDate__c = ibL[0].djdate;
                        for (InstrumentConfirmationBean ib  :ibL ) {

                          if( prodMap.get(ib.nccode) == '' )  return  Utils.getRestReturnMessage(false,'单号: '+ibL[0].djh+'salesforce 没有对应的产品!产品编码:'+ib.nccode +Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

                          InstrumentConfirmationD__c icfd = new InstrumentConfirmationD__c();
                          ///出库单号 出库明细PK 序列号 批次号
                          String k = ib.djh+ib.exWarehouseDetail+ib.emi+ib.vbatchcode; 
                          if(infdIDMap.containsKey(  k  )){
                            icfd.Id = infdIDMap.get( k );
                          }
                          icfd.ExWarehouse__c = ib.djh ;
                          icfd.IMEINumber__c = ib.emi;                    
                          icfd.Product__c = prodMap.get(ib.nccode);
                          icfd.Ts__c = ib.ts;
                          icfd.Only__c = k;
                          icfdList.add(icfd);

                        }
                        icfList.add(icf);



                    }

                    if(icfList.size() > 0){
                      upsert  icfList;
                      Map<String,String> outMapId = new Map<String,String>();
                      for ( InstrumentConfirmation__c icf : icfList) {
                          outMapId.put(icf.ExWarehouse__c,icf.Id);
                      }

                      for(InstrumentConfirmationD__c icfd :icfdList){

                        icfd.InstrumentConfirmation__c = outMapId.get(icfd.ExWarehouse__c);

                      }


                      upsert icfdList;
                    }



		              
	            	}catch (Exception e) {
	            	    	
	            	    Database.rollback(sp);
	            	    System.debug(e.getMessage());
	            	    System.debug(e.getStackTraceString());

                    return  Utils.getRestReturnMessage(false,'保存失败:  '+e.getMessage() +e.getStackTraceString()+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());
	            	}
	            	
	                               
	            }else{
                return  Utils.getRestReturnMessage(false,'获取出库数据失败 '+ String.valueOf(rs.get('result_msg'))+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());
              }
	        }else{
                return  Utils.getRestReturnMessage(false,'获取出库数据失败 '+ String.valueOf(r.get('msg'))+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

          }
        }else{
                return  Utils.getRestReturnMessage(false,'获取出库数据失败 '+ res.getBody()+Datetime.valueOf(Utils.MIN_DATE_TIME),new List<Map<String ,String>>());

        }

        return Utils.getRestReturnMessage(false,'保存成功!',new List<Map<String ,String>>());
    }
    global class InstrumentConfirmationBean{

    //	global String productId;//产品Id 
    	global String nccode ;//存货编码
    	global String exWarehouse;//出库单号
    	global Datetime  ts;//修改日期
    	global String isSingle ;//是否单机
    	global String emi; //机身号 IMEINumber__c
    	global String status ;//状态OpponentStatus__c 
    //	global String account ; //终端客户Id
    	global String account_pk ; //终端客户pk
    	global String payaccount_pk; // 开票客户PK 
    	global String exWarehouseDetail ; // 出库单明细
    	global String icid ;//记录Id 
      global String djh ;//出库单号
      global String vbatchcode ;//批次
      global string company ; //出库公司 
      global Date djdate; 



    	global InstrumentConfirmationBean(Map<String,Object> o ,String comp ){
    		nccode = String.valueOf(o.get('nccode'));
    		exWarehouse = String.valueOf(o.get('cgeneralhid'));
    		ts = Datetime.valueOf(String.valueOf(o.get('tlastmoditime')));
    		isSingle = '否';
    		emi = String.valueOf(o.get('selfno'));
    		account_pk = String.valueOf(o.get('nciccode'));
    		payaccount_pk = String.valueOf(o.get('payaccount'));
    		exWarehouseDetail = String.valueOf(o.get('cgeneralbid'));
        djh = String.valueOf(o.get('djh'));
        vbatchcode = String.valueOf(o.get('vbatchcode'));
        company = comp;
        djdate = Date.valueOf(String.valueOf(o.get('djdate')));
    	} 

    }
    global static String getSql(){

    	return 'select distinct h.vuserdef9 ,g.unitcode ,b.vbatchcode,  h.tlastmoditime ,  h.cgeneralhid ,  h.dbilldate djdate,  h.daccountdate signdate, '
    	+'d.vbilltypename ,  h.vbillcode djh,  s.rdname type,  nvl(k.pk_cubasdoc, h.pk_defdoc7)  payaccount,  h.pk_defdoc7 nciccode ,'
    	+'  h.vnote ,  c.invcode nccode,  c.invmnecode serialno,  '
    	+' c.invname ,  c.invspec  spec ,  c.invtype model,  x.vserialcode selfno,  \'1\' as num,  c.def6 swjhdj,  b.cgeneralbid  , '
    	+' (select p1.user_name from sm_user p1 where p1.cuserid = h.coperatorid and p1.pk_corp = \'0001\' ) createpsn, '
    	+' (select p2.user_name from sm_user p2 where p2.cuserid = h.cregister and p2.pk_corp = \'0001\') signpsn  from ic_general_h H  '
		  +'inner join IC_GENERAL_B B   on H.CGENERALHID = B.CGENERALHID  left join ic_general_bb2 x  on b.cgeneralbid = x.coutbillbodyid '
 	    +'left join bd_cumandoc k  on h.ccustomerid = k.pk_cumandoc  left join bd_cubasdoc kb  on nvl(k.pk_cubasdoc, h.pk_defdoc7) = kb.pk_cubasdoc '
  		+'left join bd_rdcl s  on h.cdispatcherid = s.pk_rdcl  inner join bd_corp g  on h.pk_corp = g.pk_corp  inner join ic_billtype d '
    	+'on h.cbilltypecode = d.cbilltypecode  inner join bd_invbasdoc c  on b.cinvbasid = c.pk_invbasdoc  left join bd_busitype y '
    	+'on h.cbiztype = y.pk_busitype  where H.DR = 0  and b.dr = 0  and nvl(x.dr, 0) = 0  and nvl(y.dr, 0) = 0   and h.fbillflag <> 2  '
    	+'and (c.invcode like \'30%\' OR c.invcode like \'10%\' OR     c.invcode like \'12%\')  and ((H.cbilltypecode = \'4C\' and  '
    	+'(y.businame LIKE \'%仪器销售%\' or y.businame like \'%出口流程\'))    or (H.cbilltypecode = \'4D\' '
    	+'and s.rdname = \'资产公司转固\' and    h.pk_corp in (\'1001\', \'1006\', \'1011\', \'1016\'))   '
    	+'or    (H.cbilltypecode = \'4D\' and   h.cdptid in (select pk_deptdoc    '
    	+'from bd_deptdoc      '
    	+'where substr(deptcode, 5, 2) = \'09\') and   '
     	+'h.pk_corp not in (\'1001\', \'1006\', \'1011\', \'1016\')) '
        +' or (H.cbilltypecode = \'4H\' AND s.rdname = \'借还货出库\')  '
      	+'or (H.cbilltypecode = \'4I\' AND s.rdname = \'其他出库\') OR  '
     	+'(H.cbilltypecode = \'4I\' AND     H.PK_CORP in (\'1001\', \'1006\', \'1011\', \'1016\') '
 		+'AND     s.rdname in (\'资产公司转固\', \'资产内部转固\') and '
     	+'h.cdptid in '
      	+'(select pk_deptdoc    from bd_deptdoc     where substr( regexp_replace(deptcode,\'[^0-9]\'),0,2) = \'09\'))) '
      	+'and b.cinvbasid  = \'0001A0100000000B0MZR\' and kb.custprop=\'0\' ';
    }
    */
}